package com.freewheelycheckin.server.servlets;

import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.freewheelycheckin.server.models.LocLogRecord;
import com.freewheelycheckin.server.services.LocLogRecordDao;
import com.google.gson.Gson;

public class LocLogServlet extends HttpServlet {

	private final int SAVE_LOG_REC=0;
	private final int SHOW_LOG_REC=1;
	private final int DELETE_ALL_RECS=7583262;
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Override
	protected void doGet(HttpServletRequest req,HttpServletResponse resp){
		doPost(req,resp);
	}
	@Override
    protected void doPost(HttpServletRequest req,HttpServletResponse resp){
		int opCode=-1;
		String respText="";
		try{
			opCode=Integer.parseInt(req.getParameter("opcode"));
		}
		catch(Exception e){
			e.printStackTrace();
			respText= e.getMessage();
			
		}
		switch(opCode){
			case SAVE_LOG_REC:
				respText=saveLogRec(req);
				break;
			case SHOW_LOG_REC:
				Gson gson= new Gson();
				respText=gson.toJson((new LocLogRecordDao()).listAll() );
				break;
			case DELETE_ALL_RECS:
				respText=deleteAllrecs();
		}
		resp.setHeader("Cache-Control", "no-cache");
		resp.setHeader("Content-Type", "json");
		PrintWriter writer=null;
		try{
			writer=resp.getWriter();
		}
		catch(Exception e){
			e.printStackTrace();
			respText= e.getMessage();
		}
		writer.append(respText);
		try{
			resp.flushBuffer();
		}
		catch(Exception e){
			e.printStackTrace();
			
		}
	}
	
	private String saveLogRec(HttpServletRequest req){
		LocLogRecord rec = new LocLogRecord();
		LocLogRecordDao dao= new LocLogRecordDao();
		String returnVal="";
		if (dao.getCurrentUser()!=null){
			rec.setUser(dao.getCurrentUser());
			rec.setLat(Double.parseDouble(req.getParameter("lat")));
			rec.setLongi(Double.parseDouble(req.getParameter("longi")));
			rec.setComment(req.getParameter("comment"));
			dao.put(rec);
			returnVal= "Saved succesfully";
		}
		else{
			
			returnVal="User Not recognized";
		}
		return returnVal;
	}
	private String deleteAllrecs(){
		LocLogRecordDao dao= new LocLogRecordDao();
		dao.deleteAll(dao.listAll());
		return "All records deleted";
	}

}
